/**
 * 
 */
package br.ufrgs.inf.cwsmart.data;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import br.ufrgs.inf.cwsmart.exception.FrameworkException;

/**
 * @author Rodrigo S Lumertz
 *
 */
public class DataMartDBConnection {

	private static DataMartDBConnection instance = null;
	private Connection dbConnection = null;
	
	private DataMartDBConnection() {
				
	}
	
	public synchronized static DataMartDBConnection getInstance() {
		if (instance == null)
			instance = new DataMartDBConnection();
		return instance;
	}

	public Connection getConnection() throws FrameworkException {	
		
		if (dbConnection == null) {
			Properties props = new Properties();
			
			//try retrieve data from file
	        try {
	            
	        	props.load(new FileInputStream("config//mart.config"));

	        	//mart property is mandatory
	        	if (props.getProperty("datamart_db") != null) {
	        		Class.forName("org.postgresql.Driver");
	    			this.dbConnection = DriverManager.getConnection("jdbc:postgresql://" + props.getProperty("datamart_db"));
	        	} else {
	        		throw new FrameworkException(FrameworkException.ErrorCode.DATAMART_DB_NOT_FOUND);
	        	}        	
	        	
	        } catch (IOException e) {
	        	throw new FrameworkException(FrameworkException.ErrorCode.MART_CONFIG_FILE_NOT_FOUND);
	        } catch (FrameworkException e) {
	        	throw e;
	        } catch (Exception e) {        	
	        	throw new FrameworkException(FrameworkException.ErrorCode.DB_CONNECTION_ERROR);
			} 
		}
		
		return dbConnection; 
	}
}